package com.brambila.map;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.brambila.clickable.ItensQuantity;
import com.brambila.interfaces.IObjectsName;
import com.brambila.releaseme.Game;

public class JsonReader implements IObjectsName{

	private String worldNumber;
	private String levelNumber;

	private JsonReader() {
	}

	private static JsonReader instance;

	public static JsonReader getInstance() {

		if (instance == null)
			instance = new JsonReader();

		return instance;
	}

	public String[] getLevel(String worldNumber, String levelNumber) {

		this.levelNumber = levelNumber;
		this.worldNumber = worldNumber;

		String fileDirectory = loadJSONFromAssets();
		String[] level;

		try {

			JSONObject jsonObject = new JSONObject(fileDirectory);
			JSONObject currentLevel = jsonObject.getJSONObject(ILEVEL);
			JSONArray jsonArray = currentLevel.getJSONArray(IMAP);

			level = new String[jsonArray.length()];

			for (int i = 0; i < level.length; i++) {
				level[i] = (String) jsonArray.get(i);
			}
			
			//QUANTIDADE DE ITENS
			JSONObject itens = jsonObject.getJSONObject(IOBJECTS);
			String flags = (String) itens.get(IFLAG);
			String removeBomb = (String) itens.get(IREMOVEBOMB);
			String signal = (String) itens.get(ISIGNAL);
			
			//Criar a quantidade de itens
			ItensQuantity.getInsance(flags, removeBomb, signal);

		} catch (Exception e) {
			Log.i("TAG", "THE FILE TO READ WASN'T FOUND");
			Log.i("TAG", "DIRECTORY" + fileDirectory);
			e.printStackTrace();
			return null;
		}
		
		return level;
	}

	private String loadJSONFromAssets() {

		String fileDirectory = null;

		try {
			InputStream is = Game.getContext_MainActivity().getAssets().open("mundo" + worldNumber + "_fase" + levelNumber + ".txt");

			int size = is.available();

			byte[] buffer = new byte[size];

			is.read(buffer, 0, buffer.length);

			is.close();

			fileDirectory = new String(buffer, "UTF-8");

		} catch (IOException ex) {
			return null;
		}

		return fileDirectory;
	}
}
